package com.szp.springbootvue.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.sun.deploy.net.HttpResponse;
import com.szp.springbootvue.utils.SecurityResult;
import com.szp.springbootvue.utils.UserTokenUtil;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import org.omg.IOP.ServiceContextHelper;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.filter.GenericFilterBean;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;
import java.util.List;

public class JwtFilter extends GenericFilterBean {

    /*首先从请求头中提取出 authorization 字段，这个字段对应的value就是用户的token。
    将提取出来的token字符串转换为一个Claims对象，
    再从Claims对象中提取出当前用户名和用户角色，
    创建一个UsernamePasswordAuthenticationToken放到当前的Context中，
    然后执行过滤链使请求继续执行下去。*/
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest)servletRequest;
        String jwtToken = req.getHeader("authorization");
        if (jwtToken == null) {//没有带jwt token的时候，直接放行，适用于接口放行，比如注册
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }
        System.out.println(jwtToken);
        Claims claims = Jwts.parser().setSigningKey("sang@123").parseClaimsJws(jwtToken.replace("Bearer","")).getBody();
        String username = claims.getSubject();
        //如果已经失效了就不在继续
        if(/*UserTokenUtil.isUserTokenAlive(username)*/true){
            List<GrantedAuthority> authorities = AuthorityUtils.commaSeparatedStringToAuthorityList((String) claims.get("authorities"));
            //已经下发了token说明用户名密码已经验证成功，此时直接将携带的权限信息进行解压就可以了
            UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(username, null, authorities);
            SecurityContextHolder.getContext().setAuthentication(token);
            filterChain.doFilter(req,servletResponse);
        }else {
            SecurityResult.creatReturnMsg(servletResponse,"403");
        }


    }
}
